﻿
namespace Huirui.Cavan.Presentation.Seedwork
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;
    using System.Web.Mvc;
    using Huirui.Cavan.Core.MyException;
    using Huirui.Cavan.Core.Extension;
    using Huirui.Cavan.Core.Message;

    /// <summary>
    ///     Stores Exception in the controller.model.Messages collection
    ///     and redirects to Error screen (instead of breakdown). 
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class ExceptionHandlerAttribute : ActionFilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (filterContext.Exception is DaoException
                || filterContext.Exception.InnerException is DaoException)
            {
                filterContext.Controller.Log().Fatal(filterContext.Exception);
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.Redirect(@"~\NotAvailable.aspx");
                return;
            }
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var action = (string)filterContext.RouteData.Values["action"];
            var controller = filterContext.Controller as ICoreController<ICoreModel>;

            var model = new ExceptionModel();

            model.Messages.AddException(controller,
                "Exception",
                filterContext.Exception);
            model.MasterModel.ControllerName = controllerName;
            model.MasterModel.CurrentAction = action;
            if (controller.Is())
            {
                var result = new ViewResult
                {
                    ViewData = new ViewDataDictionary<IWebModel>(model),
                    ViewName = @"~\Views\Error\Error.cshtml",
                };
                filterContext.Result = result;
            }
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
        }
    }
}